package com.market.cash.ui.activity

import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.market.cash.R
import com.market.cash.configs.CashRootConfigs
import com.market.cash.databinding.CashUserInfoBinding
import com.market.cash.pro.ProActivity
import com.market.cash.ui.presenter.CashRootUploadPresenter
import com.market.cash.ui.view.ICashRootUploadView
import com.market.cash.utils.CashRootDateUtil
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.dialog.CashRootBirthdayDialog
import com.market.cash.utils.dialog.CashRootLanguageDialog
import com.market.cash.utils.dialog.CashRootPhotoDialog
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.CashRootCustomDataHelper
import com.market.cash.utils.imgcovert.ImageConvert
import com.market.cash.utils.language.LocaleContract
import com.market.cash.utils.language.MultiLanguages
import com.market.cash.utils.log.CashRootLog
import org.json.JSONObject
import java.util.Locale

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/28 18:11
 * @Annotation：个人信息
 */
class UserInfoActivity: ProActivity(), ICashRootUploadView {
    lateinit var binding: CashUserInfoBinding
    private var presenter: CashRootUploadPresenter? = null

    private var photoDialog: CashRootPhotoDialog? = null
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    //出生日期选择
    private var birthdayDialog: CashRootBirthdayDialog? = null

    override fun getCashRootRootView(): View {
        binding = CashUserInfoBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F9F9F9"))
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTextTitle(getString(R.string.user_info_title))
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)

        if (CashRootConfigs.isTanz()){
            binding.languageLayout.visibility = View.VISIBLE
        } else {
            binding.languageLayout.visibility = View.GONE
        }
    }

    override fun initCashRootListener() {
        //客服
        rootViewBinding.imgKefu.setOnClickListener {
            KefuActivity.start(this,"User Information Page")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"User Information Page")
            if (binding.editName.isFocused){
                binding.editName.clearFocus()
            }
        }
        binding.parentLayout.setOnClickListener {
            if (binding.editName.isFocused){
                binding.editName.clearFocus()
            }
        }
        binding.imgAvatar.setOnClickListener {
            if (binding.editName.isFocused){
                binding.editName.clearFocus()
            }
            if (presenter == null){
                presenter = CashRootUploadPresenter(this)
            }
            showCashRootPhotoDialog("User Information Page")
        }
        //昵称
        binding.editName.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点
                }
                else -> {//失去焦点
                    val userName = binding.editName.text.toString().trim()
                    if (userName.isNotEmpty()){
                        CashRootCustomDataHelper.saveCashRootCustomUserNameAction(userName)
                    }
                }
            }
        }

        binding.editName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editName.clearFocus()
                true
            }
            false
        }

        //选择生日(只能修改一次)
        binding.textBirthday.setOnClickListener {
            if (binding.editName.isFocused){
                binding.editName.clearFocus()
            }
            showCashRootBirthDialog()
        }

        //选择语言
        binding.languageLayout.setOnClickListener {
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LANGUAGE_CHECK,"User Information Page")
            showCashRootLanguageDialog()
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        CashRootLog.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showCashRootLoading(isTOuchOut = false, isCancel = false)
                        presenter!!.onCashRootUploadImageAction(localPath)
                    }
                }
            } else {
                CashRootLog.e("No media selected")
            }
        }
    }

    override fun initCashRootData() {
        setCashRootUserInfo()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }

        //当前语言
        val curtLocale = MultiLanguages.getAppLanguage(this)
        when(curtLocale.language){
            LocaleContract.getSwahiliLocale().language -> {//坦桑
                binding.textLanguage.text = getString(R.string.language_tanzania).uppercase()
            }
            else -> {
                binding.textLanguage.text = getString(R.string.language_english).uppercase()
            }
        }
    }

    /**
     * 设置用户信息
     */
    private fun setCashRootUserInfo(){
        val avatarUrl = CashRootCustomDataHelper.getCashRootCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            CashRootImageUtil.instance.loadImageUrl(this,binding.imgAvatar,avatarUrl)
        } else {
            binding.imgAvatar.setImageResource(R.mipmap.cash_holder)
        }
        binding.editName.setText(CashRootCustomDataHelper.getCashRootCustomUserName())

        //生日只能设置一次
        val birthday = CashRootCustomDataHelper.getCashRootCustomUserBirthday()
        if (birthday.isEmpty()){
            binding.imgEnable.visibility = View.VISIBLE
            binding.textBirthday.isEnabled = true
        } else {
            binding.imgEnable.visibility = View.GONE
            binding.textBirthday.isEnabled = false

            val showBirthday = CashRootDateUtil.getFormatTime(birthday.toLong() * 1000,"dd/MM/yyyy")
            binding.textBirthday.text = showBirthday
        }
    }

    /**
     * 相机、相册
     */
    private fun showCashRootPhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = CashRootPhotoDialog(this,eventRemark,object : CashRootPhotoDialog.IDialogCallback{
                override fun openCamera() {
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CAMERA,eventRemark)
                    openCashRootCamera()
                }
                override fun openAlbum() {
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_ALBUM,eventRemark)
                    openCashRootAlbum()
                }
            })
            photoDialog!!.setCancelable(true)
            photoDialog!!.setCanceledOnTouchOutside(true)
        }
        photoDialog!!.show()
    }

    /**
     * 打开相册
     */
    private fun openCashRootAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 打开相机
     */
    private fun openCashRootCamera(){
        faceCameraResultLauncher.launch(Intent(this, CameraSelfieActivity::class.java))
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                CashRootLog.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                CashRootCustomDataHelper.saveCashRootCustomUserAvatar(imgUrl)
            }
        }
    }

    /**
     * 图片上传成功
     */
    override fun showCashRootUploadImageSuccess(imgPath: String, imgUrl: String) {
        CashRootCustomDataHelper.saveCashRootCustomUserAvatar(imgUrl)
    }

    /**
     * 选择出生日期
     */
    private fun showCashRootBirthDialog(){
        if (birthdayDialog == null){
            birthdayDialog = CashRootBirthdayDialog(this,"User Information Page",object : CashRootBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    val timeInMillis = selectDate.optLong("timeInMillis")
                    val value = CashRootDateUtil.getFormatTime(timeInMillis,"dd/MM/yyyy")
                    binding.textBirthday.text = value
                    CashRootCustomDataHelper.saveCashRootCustomUserBirthday("${timeInMillis / 1000}")
                }
            })
        }
        birthdayDialog!!.show()
    }

    /**
     * 显示选择语言
     */
    private fun showCashRootLanguageDialog(){
        val languageDialog = CashRootLanguageDialog(this,"User Information Page",object : CashRootLanguageDialog.IDialogCallback{
            override fun settingLanguageEnglish() {
                saveSelectLanguageAction(LocaleContract.getEnglishLocale())
            }
            override fun settingLanguageSwahili() {
                saveSelectLanguageAction(LocaleContract.getSwahiliLocale())
            }
        })
        languageDialog.setCancelable(true)
        languageDialog.setCanceledOnTouchOutside(true)
        languageDialog.show()
    }

    /**
     * 设置语言
     */
    private fun saveSelectLanguageAction(newLocale: Locale){
        //是否需要重启
        val restart = MultiLanguages.setAppLanguage(this,newLocale)
        if (restart) {
            // 我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果
            onIntent(SplashActivity::class.java)
            overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
        }
    }

    override fun onCashRootEvent(event: CashRootEventData) {
        super.onCashRootEvent(event)
        when(event.eventType){
            CashRootEventData.TYPE.CASHROOT_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                setCashRootUserInfo()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_INFORMATION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_INFORMATION_END)
    }
}